package com.ficus.road.maintain.service;

import com.ficus.road.maintain.core.model.Camera;
import com.ficus.road.maintain.core.model.Car;
import com.ficus.road.maintain.dao.CameraDao;
import com.ficus.road.maintain.dao.CarDao;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author jinbiao.he
 * @Since 2021/4/8 上午11:19
 */
@Service
public class CameraService {

    @Autowired
    private CarDao carDao;
    @Autowired
    private CameraDao cameraDao;

    public String registerCamera(String carId, List<String> cameraIds) {
        Criteria criteria = Criteria.where("carId").is(carId);
        Query query = Query.query(criteria);
        List<Camera> cameraList = cameraDao.findByQuery(query);
        if (CollectionUtils.isNotEmpty(cameraList)) {
            List<String> collect = cameraList.stream().map(Camera::getId).collect(Collectors.toList());
            cameraIds.removeAll(collect);
        }
        if (CollectionUtils.isEmpty(cameraIds)) {
            return null;
        }

        List<Camera> cameraList1 = new ArrayList<>();
        long curTime = System.currentTimeMillis() / 1000;
        for (String cameraId : cameraIds) {
            cameraList1.add(Camera.builder()
                    .carId(carId)
                    .id(cameraId)
                    .creationTime(curTime)
                    .lastModificationTime(curTime)
                    .build());
        }
        Collection<Camera> cameras = cameraDao.insert(cameraList1);
        return cameras.stream().map(Camera::getId).collect(Collectors.joining());
    }

    public String registerCar(Car car) {
        Criteria criteria = Criteria.where("plateNo").is(car.getPlateNo());
        Query query = Query.query(criteria);
        Car one = carDao.findOne(query);
        if (one != null) {
            return one.getId();
        }

        long time = System.currentTimeMillis() / 1000;
        car.setCreationTime(time);
        car.setLastModificationTime(time);
        Car car1 = carDao.insert(car);
        return car1.getId();
    }

    public List<Car> queryCar(Query query) {
        query.with(new Sort(Sort.Direction.DESC, "creationTime"));
        return carDao.findByQuery(query);
    }

    public List<Camera> queryCamera(Query query) {
        query.with(new Sort(Sort.Direction.DESC, "creationTime"));
        return cameraDao.findByQuery(query);
    }

    public Camera findByCameraId(String cameraId) {
        return cameraDao.fetch(cameraId);
    }
}
